<?php
/**
 * Created by PhpStorm.
 * User: 黑盒子
 * Date: 2020/11/16
 * Time: 23:12
 */

namespace app\api\controller;

use app\common\exception\ApiException;
use think\Db;
use think\Model;

class Setting extends Base
{
    public function select()
    {
        $settings = \app\api\model\Setting::field('type,content')->select();
        return json(['success' => 1, 'list' => $settings]);
    }

    public function save()
    {
        $data = input('data','[]');

        if ($data) {
            $data = json_decode($data, true);
        }

        $must_type = [
            'group_qrcode' => '交流群二维码',
            'logo' => '网页logo',
            'web_name' => '网站标题',
            'swiper' => '幻灯片',
            'footer_text' => '底部提示文本'
        ];

        if (!empty($data)) {
            $type_arr = array_column($data,'type');

            foreach ($must_type as $k => $v) {
                if (!in_array($k, $type_arr)) {
                    throw new ApiException(['msg' => '请填写'.$v]);
                }
            }

            foreach ($data as $k => $datum) {
                if ($datum['type'] == 'swiper' || $datum['type'] == 'logo' || $datum['type'] == 'group_qrcode') {
                    $data[$k]['content'] = json_encode($datum['content']);
                }
            }

            Db::startTrans();
            try {
                \app\api\model\Setting::where('id','>','0')->delete();
                $setting = new \app\api\model\Setting();
                $setting->saveAll($data);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                throw new ApiException(['msg' => '操作失败']);
            }
        } else {
            throw new ApiException(['msg' => '设置填写不完整']);
        }

        return json(['success' => 1, 'msg' => '操作成功']);
    }
}